package BookCreated;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import BookDB.h2DAO;

@WebServlet("/FileUpLoad")
public class FileUpLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		HttpSession session = request.getSession();
		Books book = (Books) session.getAttribute("sessionBook");
//		System.out.println(book.getBookID());
	
		
		// 保存路徑
		String savePath = getServletContext().getRealPath("/images");
		File saveDir = new File(savePath);
		// 如果目錄不存在，就創建目錄
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		// System.out.println(saveDir.getPath());
		// 創建文件上傳核心類
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 設置編碼
		sfu.setHeaderEncoding("UTF-8");
		// 設置上傳的單個文件的最大字節數为2M
		sfu.setFileSizeMax(1024 * 1024 * 2);
		// 設置整個表單的最大字節數为10M
		sfu.setSizeMax(1024 * 1024 * 10);

		try {
			// 處理表單請求
			List<FileItem> itemList = null;
			itemList = sfu.parseRequest(request);

			for (FileItem fileItem : itemList) {
				// 對應表單中的控件的name
				String fieldName = fileItem.getFieldName();
				// 如果是普通表單控件
				if (fileItem.isFormField()) {
					String value = fileItem.getString();
					// 重新編碼,解决亂碼
					value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
					System.out.println("普通內容：" + fieldName + "=" + value);
					// 上傳文件
				} else {
					// 獲得文件大小
					Long size = fileItem.getSize();
					// 獲得文件名
					String fileName = fileItem.getName();

					// 設置不允許上傳的文件格式
					if (fileName.endsWith(".exe")) {
						request.setAttribute("msg", "不允許上傳的類型！");
					} else {
						// 將文件保存到指定的路徑
						fileName = book.getBookID() + ".jpg";
						File file = new File(savePath, fileName);
						fileItem.write(file);
//						System.out.println(savePath);
//						System.out.println(fileName);
						request.setAttribute("msg", "上傳成功！");
					}
				}
			}
		} catch (FileSizeLimitExceededException e) {
			request.setAttribute("msg", "文件太大");
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 上傳完畢後 轉發到首頁
		// request.getRequestDispatcher("/index.jsp").forward(request,
		// response);
		PrintWriter w = response.getWriter();
		w.print("Update is 	file OK. (上載文入作.)"
				+ "<p> <input type=\"button\" value=\"返回上層\" onclick=\";history.go(-1);\">");

	}
}
